package com.leon.alishop.spider.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import net.sf.json.JSONObject;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.leon.alishop.core.enumeration.AttrInfoTypeEnum;
import com.leon.alishop.core.enumeration.GoodsStatusEnum;
import com.leon.alishop.core.model.AttributesModel;
import com.leon.alishop.core.service.AttributesService;
import com.leon.alishop.core.service.GoodsAttrService;
import com.leon.alishop.core.service.GoodsService;
import com.leon.alishop.core.service.GoodsSkuService;
import com.leon.alishop.model.AttrValInfo;
import com.leon.alishop.model.GoodsInfo;
import com.leon.alishop.model.GoodsSku;
import com.leon.alishop.model.ProviderInfo;
import com.leon.alishop.spider.model.TaobaoGoodsInfo;
import com.leon.alishop.spider.model.TaobaoGoodsSKU;

@Service("taobaoGoodsService")
public class TaobaoGoodsServiceImpl implements TaobaoGoodsService {
	private static Logger log = LoggerFactory.getLogger(TaobaoGoodsServiceImpl.class);
	
	/**
	 * 是否有效
	 * @param tbGoods
	 * @return
	 */
	public static boolean isValidCrawlGoods(TaobaoGoodsInfo tbGoods){
		return tbGoods.getProviderTaobaoGoodsId() != null
				&& tbGoods.getProviderGoodsName() != null
				&& tbGoods.getProviderGoodsPrice() != null
				&& !CollectionUtils.isEmpty(tbGoods.getTaobaoGoodsSkuList());
	}
	
	@Override
	public int insertTaobaoGoodsSku(ProviderInfo pro,TaobaoGoodsInfo taobaoGoodsInfo) {
		return 0;
	}

	@Override
	public int insertTaobaoGoodsSku(ProviderInfo pro,List<TaobaoGoodsInfo> taobaoGoodsInfos,boolean resetHistoryFlag) {
		//////////////////////////////////
		// 更新商品信息
		if(resetHistoryFlag){
			goodsService.resetGoodsScoreAndStatus(pro.getId());
		}
		/////////////////////////////////
		if(taobaoGoodsInfos == null || taobaoGoodsInfos.size()==0)
			return 0;
		Map<String,String[]> imgInfoMap;
//		List<TaobaoGoodsInfo> invalidGoodsList = new ArrayList<TaobaoGoodsInfo>();
		GoodsInfo goods;
		List<TaobaoGoodsSKU> tbSkus;
		List<AttributesModel> attributes = null;
		HashMap<Integer, AttributesModel> attributeMap = null;
		AttrValInfo attrValInfo;
		String imgInfoJson = null;
		AttributesModel am;
		Map<String,String> normalAttr;
		List<GoodsSku> goodsSkuList;
		GoodsSku goodsSku;
		int stock = 0;
		int favScore = 0;
		int cur = 1;
		int size = taobaoGoodsInfos.size();
		for (TaobaoGoodsInfo tbGoods : taobaoGoodsInfos) {
			log.info("更新商品：["+pro.getId()+"-"+cur+"/"+size+"-"+tbGoods.getProviderTaobaoGoodsId()+"]");
			cur++;
			attributes = new ArrayList<AttributesModel>();
			attributeMap = new HashMap<Integer, AttributesModel>();
			favScore ++;
			if(!isValidCrawlGoods(tbGoods)){
//				invalidGoodsList.add(tbGoods);
				continue;
			}
			////////////////////////////////////////////////////////////////
			// 图片
			imgInfoMap = new HashMap<String, String[]>();
			if(tbGoods.getThumbnailUrls()!=null 
					&& tbGoods.getThumbnailUrls().length>0){
				imgInfoMap.put("min", tbGoods.getThumbnailUrls());
			}
			if(tbGoods.getBigImgUrls()!=null
					&& tbGoods.getBigImgUrls().length>0){
				imgInfoMap.put("big", tbGoods.getBigImgUrls());
			}
			imgInfoJson = JSONObject.fromObject(imgInfoMap).toString();
			////////////////////////////////////////////////////////////////
			// SKU库存 和 属性
			tbSkus = tbGoods.getTaobaoGoodsSkuList();
			if(null != tbSkus && tbSkus.size()>0){
				for (TaobaoGoodsSKU _sku : tbSkus) {
					stock += _sku.getStock();
					//尺码
					if(attributeMap.containsKey(_sku.getSizeId())){
						am = attributeMap.get(_sku.getSizeId());
					}else{
						am = new AttributesModel();
						attributeMap.put(_sku.getSizeId(), am);
					}
					am.setAttrType(AttrInfoTypeEnum.SIZE.ordinal());
					am.setAttrName("尺码");
					am.setTaobaoId(_sku.getSizeId());
					if(!containAttrValName(am.getAttrValList(), _sku.getSizeValName())){
						attrValInfo = new AttrValInfo();
						attrValInfo.setTaobaoId(_sku.getSizeValId());
						attrValInfo.setValueName(_sku.getSizeValName());
						attrValInfo.setValueType(am.getAttrType());
						am.addAttrVal(attrValInfo);
					}
					//颜色
					if(attributeMap.containsKey(_sku.getColorId())){
						am = attributeMap.get(_sku.getColorId());
					}else{
						am = new AttributesModel();
						attributeMap.put(_sku.getColorId(), am);
					}
					am.setAttrType(AttrInfoTypeEnum.COLOR.ordinal());
					am.setAttrName("颜色");
					am.setTaobaoId(_sku.getColorId());
					if(!containAttrValName(am.getAttrValList(), _sku.getColorValName())){
						attrValInfo = new AttrValInfo();
						attrValInfo.setTaobaoId(_sku.getColorValId());
						attrValInfo.setValueName(_sku.getColorValName());
						attrValInfo.setValueType(am.getAttrType());
						am.addAttrVal(attrValInfo);
					}
				}
			}
			// 属性
			normalAttr = tbGoods.getAttributeMap();
			if(null != normalAttr && normalAttr.size()>0){
				for (Entry<String, String> o : normalAttr.entrySet()) {
					if("颜色".equals(o.getKey())
							|| "尺码".equals(o.getKey())
							|| "价格".equals(o.getKey())
							|| "颜色分类".equals(o.getKey())
							|| o.getKey().indexOf("颜色")>=0
							|| o.getKey().indexOf("价格")>=0
							|| "货号".equalsIgnoreCase(o.getKey()))
						continue;
					am = new AttributesModel();
					am.setAttrType(AttrInfoTypeEnum.NORMAL.ordinal());
					am.setAttrName(o.getKey());
					am.setTaobaoId(0);
					attrValInfo = new AttrValInfo();
					attrValInfo.setTaobaoId(0);
					attrValInfo.setValueName(o.getValue());
					attrValInfo.setValueType(am.getAttrType());
					am.addAttrVal(attrValInfo);
					attributes.add(am);
				}
			}
			attributes.addAll(attributeMap.values());
			attributes = attributesService.insertCrawlAttribute(attributes);
			////////////////////////////////////////////////////////////////
			// 保存商品
			goods = ((GoodsInfo)tbGoods).clone();
			goods.setProviderStatus(GoodsStatusEnum.ONLINE.ordinal());
			goods.setProviderAreaId(pro.getAreaId());
			goods.setProviderId(pro.getId());
			goods.setProviderGoodsImgInfo(imgInfoJson);
			goods.setProviderStock(stock);
			goods.setFavScore(favScore);
			goods.setProviderStatus(GoodsStatusEnum.ONLINE.ordinal());
			goodsService.insertGoodsInfoForCrawl(goods);
			
			// 保存SKU
			if(null != tbSkus && tbSkus.size()>0){
				goodsSkuList = new ArrayList<GoodsSku>();
				for (TaobaoGoodsSKU _sku : tbSkus) {
					am = attributesService.findAttributeByNameAndType(_sku.getColorName(), AttrInfoTypeEnum.COLOR.ordinal());
					if(am == null)
						continue;
					attrValInfo = am.getAttrValInfo(_sku.getColorValName());
					if(null == attrValInfo)
						continue;
					goodsSku = new GoodsSku();
					goodsSku.setColorAttrValId(attrValInfo.getId());
					am = attributesService.findAttributeByNameAndType(_sku.getSizeName(), AttrInfoTypeEnum.SIZE.ordinal());
					if(am == null)
						continue;
					attrValInfo = am.getAttrValInfo(_sku.getSizeValName());
					if(null == attrValInfo)
						continue;
					goodsSku.setSizeAttrValId(attrValInfo.getId());
					goodsSku.setGoodsId(goods.getId());
					goodsSku.setProviderSkuPrice(_sku.getPrice());
					goodsSku.setProviderSkuStock(_sku.getStock());
					goodsSku.setTaobaoSkuId(_sku.getSkuId());
					goodsSkuList.add(goodsSku);
				}
				goodsSkuService.insertOrUpdateSkuListForCrawl(goodsSkuList, goods.getId());
			}
			
			// 保存属性与商品对应关系
			goodsAttrService.insertGoodsAttrRelate(goods.getId(), attributes);
		}
		return taobaoGoodsInfos.size();
	}
	
	private boolean containAttrValName(Collection<AttrValInfo> attrValInfoList,String attrValName){
		if(attrValInfoList == null)
			return false;
		for (AttrValInfo attrValInfo : attrValInfoList) {
			if(attrValInfo.getValueName().equals(attrValName))
				return true;
			
		}
		return false;
	}
	
	@Autowired
	private AttributesService attributesService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private GoodsSkuService goodsSkuService;
	@Autowired
	private GoodsAttrService goodsAttrService;
}
